package com.ydd.excel.excelserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ydd.excel.excelserver.entity.UserEntity;
import com.ydd.excel.excelserver.mapper.UserMapper;
import com.ydd.excel.excelserver.service.ExcelService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
@Service
public class ExcelServiceImpl implements ExcelService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 创建一个Excel文件，放在这里可以不用手动关闭流
        try (Workbook workbook = new XSSFWorkbook()) {
            // 创建一个Excel页
            Sheet sheet = workbook.createSheet("users");
            // 创建表头
            Row headerRow = sheet.createRow(0);
            // 给表头创建单元格并赋值
            headerRow.createCell(0).setCellValue("姓名");
            headerRow.createCell(1).setCellValue("手机号");
            headerRow.createCell(2).setCellValue("导出日期");
            headerRow.createCell(3).setCellValue("1");
            headerRow.createCell(4).setCellValue("2");
            headerRow.createCell(5).setCellValue("3");

            // 每次处理的数据量，大家可以自己调整，比如每次处理1000条
            int batchSize = 1000;
            // 最大线程数，大家可以自己调整，根据自己服务器性能来调整
            int maxThreads = 10;

            // 创建线程池
            ExecutorService executorService = Executors.newFixedThreadPool(maxThreads);

            // 查询总记录数
            int totalCount = userMapper.selectCount(null);
            // 计算总批次
            int totalBatches = (int) Math.ceil((double) totalCount / batchSize);
            // 分批次导出数据
            for (int i = 0; i < totalBatches; i++) {
                int offset = i * batchSize;
                // 提交任务
                executorService.execute(new ExcelWriterTask(sheet, offset, batchSize));
            }

            // 关闭线程池
            executorService.shutdown();
            executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); // 等待所有任务执行完毕 Long.MAX_VALUE为超时时间，可以自由设置

            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=users.xlsx");
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void add() {

        for (int i = 0; i < 100000; i++) {
            UserEntity userEntity = new UserEntity();
            userEntity.setPassword("p"+i);
            userEntity.setUsername("u"+i);
            userEntity.setStatus("1");
            userMapper.insert(userEntity);
        }
    }

    private class ExcelWriterTask implements Runnable {
        private Sheet sheet;
        private int offset;
        private int batchSize;

        public ExcelWriterTask(Sheet sheet, int offset, int batchSize) {
            this.sheet = sheet;
            this.offset = offset;
            this.batchSize = batchSize;
        }

        @Override
        public void run() {

            // 测试用，模拟处理数据的耗时
            // _________________________________________
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            // _________________________________________
            QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<UserEntity>().orderByAsc("id").last("limit " + offset + ", " + batchSize);
            // 查询数据
            List<UserEntity> users = userMapper.selectList(queryWrapper);
            // 这里要注意，写入数据的时候需要同步写入，不然会出现覆盖等问题
            synchronized (sheet) {
                int rowNum = sheet.getLastRowNum();
                for (UserEntity user : users) {
                    Row row = sheet.createRow(++rowNum);
                    row.createCell(0).setCellValue(user.getId());
                    row.createCell(1).setCellValue(user.getUsername());
                    row.createCell(2).setCellValue(user.getStatus());
                    row.createCell(3).setCellValue(user.getUsername());
                    row.createCell(4).setCellValue(user.getPassword());
                    // 加个日期是为了好验证多线程导出的结构
                    row.createCell(5).setCellValue(new Date().toString());
                }
            }
        }
    }

}
